package com.example.listenmailforfsbot;

import com.example.listenmailforfsbot.config.MailConfig;
import com.example.listenmailforfsbot.util.ListenMail;
import com.example.listenmailforfsbot.util.TextFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author dftdla
 */
@SpringBootApplication
@EnableScheduling
@RestController
public class ListenMailForFsBotApplication {

	public static final ReentrantLock LOCK = new ReentrantLock();

	public static void main(String[] args) {
		SpringApplication.run(ListenMailForFsBotApplication.class, args);
	}

	@Bean
	public TaskScheduler scheduler() {
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(10);
		taskScheduler.setThreadNamePrefix("MailServer");
		return taskScheduler;
	}

	@Resource
	private ListenMail listenMail;
	@Resource
	private MailConfig mailConfig;
	@Resource
	private TextFilter textFilter;

	@Scheduled(cron = "0/30 * * * * ? ")
	public void mailHandle() throws InterruptedException {
		System.out.println("任务执行,Time:\n\t\t" + LocalDateTime.now());
		if(LOCK.tryLock(1, TimeUnit.SECONDS)){
			System.out.println("是否持有锁:" + LOCK.isHeldByCurrentThread());
			listenMail.fetchMail();
			LOCK.unlock();
			System.out.println("释放ReentrantLock锁\n\n");
		}else{
			System.out.println("ReentrantLock锁被占用,跳过此次定时任务,Time:\n\t\t" + LocalDateTime.now() + "\n\n");
		}
	}

	@RequestMapping("/openListen")
	public String openMailListen(){
		return listenMail.startListen()?"邮件转发已开启":"邮件转发开启失败";
	}

	@RequestMapping("/closeListen")
	public String closeMailListen(){
		return listenMail.stopListen()?"邮件转发已关闭":"邮件转发关闭失败";
	}

	@RequestMapping("/statusListen")
	public String getMailStatus(){
		return !listenMail.getOpen()?"邮箱监听中":"邮箱静默中";
	}

	@RequestMapping("/mailConfig")
	public String configMail(){
		return mailConfig.toString() + "\n" + listenMail.toString();
	}

	@RequestMapping("/checkPassword")
	public String checkPassword(String password){
		return listenMail.checkPassword(password)?"密码一致":"密码不一致";
	}

	@RequestMapping("/checkWebHook")
	public String checkWebHook(String url){
		return listenMail.checkWebHook(url)?"webhook地址一致":"webhook地址不一致";
	}

	@RequestMapping("/textCheck")
	public String textCheck(String text){
		return textFilter.checkText(text);
	}

}
